Data Grid

Conditionally Format DataGrid Column Text

Description
This customization shows how to set the color of a DataGrid cell based on its value.
Variables
Table Name
Select a database table to be shown in DataGrid
Applies to
Page class
Code
  
/// 
/// This method is called when a page is loaded.
/// 
/// The object that raised the load event.
/// The object that contains the event data of the load event.
private void MyPageLoad(object sender, System.EventArgs e) 
{ 
    if (!this.IsPostBack)
    {
        System.Web.UI.WebControls.DataGrid myDataGrid = ((System.Web.UI.WebControls.DataGrid)(this.FindControlRecursively("myDataGrid")));

        // If DataGrid is found then populate it.
        if (!(myDataGrid == null))
        {

            // example of where clause is
            // whereStr = " myNumericField = 1"
            // whereStr = " myStrField = '1'"
            string whereStr = null;

            // Create orderBy clause
            BaseClasses.Data.OrderBy ob = null;

            // Set page index and size
            int pageIndex = 0;
            int pageSize = 1000;

            // Retrieving first 1000 records.               
            // Bind the result set to the DataGrid.        
            myDataGrid.DataSource = ${${Table Name}ClassName}.GetDataTable(whereStr, ob, pageIndex, pageSize);
            myDataGrid.DataBind();      
        }
    }
}
 
Applies to
Page class
Code
 
/// 
/// This method is called when DataGrid items databind.
/// Set the OnItemDataBound property of the datagrid to have a value of "MyItemDataBound"
/// This function is called everytime an item is bound to the datagrid
/// 
/// The object that raised the load event.
/// The object that contains the event data of the DataGrid items.
public void MyItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
    if (e.Item.ItemType == System.Web.UI.WebControls.ListItemType.Item || 
        e.Item.ItemType == System.Web.UI.WebControls.ListItemType.AlternatingItem)
    {
            // Check for all cells in the DataGrid.
            for(int i = 0; i < (e.Item.Cells.Count); i++)
            {
                // Customize the business logic here.
                if (e.Item.Cells[i].Text == "myValue")
                {                
                    // If cell contains text "myValue", then
                    // set the cell's back color to yellow.
                    e.Item.Cells[i].BackColor = System.Drawing.Color.Yellow;
                }
            }
    }
}
     
Applies to
CSharpPageConstructor class
Code
 
    // The following line will be inserted inside the
    // constructor for page class.
    this.Load += new System.EventHandler(MyPageLoad);    
     

Terms of Service Privacy Statement